package com.yan.controller.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

//Aop
@EnableWebSecurity
public class SecurtityConfig extends WebSecurityConfigurerAdapter {

    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问 功能页只有对应有权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")// level1这个路径只有被授予了vip1权限的人才能访问
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");


        //么有权限默认会登录页面 需要开启登录的页面
        http.formLogin();
        //定制登录页面
        http.formLogin().loginPage("/toLogin");

        http.rememberMe();//首页记住我功能
        http.csrf().disable();//关闭csrf  登录失败的原因

        //注销  调到首页  logoutUrl("/")  删除 cook
      //  http.logout().logoutUrl("/"); //注销在那个地方
        http.logout().logoutSuccessUrl("/"); //注销成功的地方
//        super.configure(http);
    }


    //认证
    //密码编码 PasswordEncoder
    //在spring secutiy 新增了很多的加密的方法
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     //   super.configure(auth);

        //从数据库读取这些即可                           new BCryptPasswordEncoder().encode("123456")  密码加密 方式是 BCryptPasswordEncoder       roles("vip2","vip3") 用户的权限正好去上面去访问
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("yanwc").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("wenc").password(new BCryptPasswordEncoder().encode("123456")).roles("vips1");

    }
}
